<?php


namespace App\LayAdmin\Controllers;


use App\LayAdmin\Components\Form;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;

class AdminUserController extends BaseController
{
    public function edit(Request $request):Response{
        $user = $request->user();
        if($request->getMethod()==Request::METHOD_POST){
            $data = $request->post('data');
            $user->name = $data['name'];
            $user->email = $data['email'];
            $user->mobile = $data['mobile'];
            if($user->save()){
                return $this->successApi();
            }
            $this->errorOptFail();
        }
        $form = new Form("/admin/edit-user");
        $form->field('name',$user->name)->textInput()->label('登录名');
        $form->field('email',$user->email)->textInput()->label('邮箱');
        $form->field('mobile',$user->mobile)->textInput()->label('手机');
        $form->submit();
        return new Response($form);
    }

    public function password(Request $request):Response{
        $user = $request->user();
        if($request->getMethod()==Request::METHOD_POST){
            $data = $request->post('data');
            if(empty($data)){
                $this->errorRequest('没有数据');
            }
            foreach ($data as $item){
                if(strlen($item)<6){
                    $this->errorRequest('密码长度不够');
                }
            }
            if($data['password']!=$data['password_confirm']){
                $this->errorRequest('确认密码不一致');
            }
            if($data['password']==$data['password_old']){
                $this->errorRequest('密码未改变');
            }

            if(!Hash::check($data['password_old'], $user->password)){
                $this->errorRequest('原密码不正确');
            }
            $user->password = Hash::make($data['password']);
            if($user->save()){
                return $this->successApi();
            }
            $this->errorOptFail();
        }
        $form = new Form("/admin/password");
        $form->field('password_old')->passwordInput()->label('旧密码');
        $form->field('password')->passwordInput()->label('新密码');
        $form->field('password_confirm')->passwordInput()->label('确认新密码');
        $form->submit();
        return new Response($form);
    }
}
